package com.example.service_oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.example.common.commonsutils.R;
import com.example.service_oss.service.OssService;
import com.example.service_oss.utils.ConstantPropertiesUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.UUID;

/**
 * @Author:tjf
 * @Description:
 */
@Log4j2
@Service
public class OssServiceImpl implements OssService {
    /**
     * 处理头像上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public R handleAvatarUpload(MultipartFile multipartFile) {
        String accessUrl;
        try{
            accessUrl = saveAvatarToAliyun(multipartFile);
        }catch (Exception e){
            log.error(e.getMessage());
            return R.error().message(e.getMessage());
        }
        return R.ok().data("avatar", accessUrl);
    }

    /**
     * 保存图片到Oss
     *
     * @param file
     * @return
     */
    private String saveAvatarToAliyun(MultipartFile file) throws Exception {
        String accessKeyId = ConstantPropertiesUtils.ACCESSKEYID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESSKEYSECRET;
        String endpoint = ConstantPropertiesUtils.ENDPOINT;
        String bucketName = ConstantPropertiesUtils.BUCKETNAME;

        // 文件名
        String fileName = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
        // 文件存储路径
        String filePath = ConstantPropertiesUtils.HOMEPATH + fileName;

        // 设置访问凭证
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);

        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        // 把用户上传的头像保存到阿里云
        ossClient.putObject(bucketName, filePath, file.getInputStream());
        if (ossClient != null) {
            ossClient.shutdown();
        }
        String avatarAccessUrl = "https://" + bucketName + "." + endpoint + "/" + filePath;
        return avatarAccessUrl;
    }
}
